﻿using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using RHD.Common.Web.Components.Filter;
using RHD.Web.Infrastructure;

namespace RHD.Common.Web.Components {
	public static class FilterExtension {
		public static MvcHtmlString Filter(this HtmlHelper htmlHelper, string id, Action<FilterBuilder> optionsHandle = null, object htmlAttributes = null) {
			TagBuilder div = new TagBuilder("div");
			div.GenerateId(id);
			if (htmlAttributes != null)
				div.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));
			id = div.Attributes["id"];

			FilterBuilder options = new FilterBuilder();
			if (optionsHandle != null)
				optionsHandle(options);

			div.InnerHtml = options.htmlContent;
			RegisterScript(htmlHelper, id, options);
			return MvcHtmlString.Create(div.ToString());
		}

		private static void RegisterScript(HtmlHelper htmlHelper, string id, FilterBuilder options) {
			StringBuilder option = new StringBuilder();
			option.AppendFormat("grid: '{0}',", options.grid);
			option.AppendFormat("btnFilter: '{0}'", options.filter);
			htmlHelper.AddScript(string.Format("$('#{0}').filter({{{1}}});", id, option));
		}
	}
}